import React, { Component } from 'react';
import PropTypes from 'prop-types';

import styles from './style.scss';
import SinglePictureUpload from './SinglePictureUpload';

export default class ImageUpload extends Component {
    static propTypes = {
        onPreview: PropTypes.func,
    };

    static defaultProps = {
        onPreview: () => undefined,
    };

    constructor(props) {
        super(props);
        this.state = {
        };
    }

    onChange = (info, idx = 0) => {
        const { onChange } = this.props;
        onChange(info, idx);
    };

    onDelete = (idx, evt) => {
        const { onDelete } = this.props;
        onDelete(idx, evt);
    };

    render() {
        let { 
            files, 
            count, 
            accept, 
            maxSize, 
            description,
        } = this.props;
        if (files && !Array.isArray(files)) {
            if (typeof files === 'string' && files.indexOf(',') !== -1) {
                files = files.split(',');
            } else {
                files = [files];
            }
        }
        const len = files && files.length || 0;
        return (
            <div className={styles.imgUpload}>
                <div className={styles.imgUploadGroup}>
                    {
                        files && files.map((item, idx) => {
                            let fileUrl;
                            if (typeof item === 'string') {
                                fileUrl = item;
                            } else {
                                fileUrl = item.download;
                            }
                            fileUrl = fileUrl || null;
                            return (
                                <SinglePictureUpload
                                    key={idx}
                                    accept={accept}
                                    maxSize={maxSize}
                                    uploadedFile={fileUrl}
                                    onDelete={(evt) => this.onDelete(idx, evt)}
                                    // onChange={(info) => this.onChange(info, idx)}
                                />
                            );
                        })
                    }
                    {
                        len < count ?
                            <SinglePictureUpload
                                accept={accept}
                                maxSize={maxSize}
                                uploadedFile={null}
                                // onDelete={(evt) => this.onDelete(len, evt)}
                                onChange={(info) => this.onChange(info, len)}
                            /> : null
                    }
                </div>
                <div className={styles.desc}>
                    {description}
                </div>
            </div>
        );
    }
}
